<template>
  <div class="dynamic-block-config-test">
    <el-card>
      <template #header>
        <h3>动态区块字段配置测试</h3>
      </template>
      
      <el-alert
        title="功能说明"
        type="info"
        description="测试区块字段配置的动态加载、保存和管理功能"
        show-icon
        :closable="false"
      />
      
      <el-divider />
      
      <el-row :gutter="24">
        <!-- 区块列表 -->
        <el-col :span="12">
          <h4>区块列表</h4>
          <div v-loading="blocksLoading">
            <el-table :data="blocks" stripe @row-click="selectBlock">
              <el-table-column prop="name" label="区块名称" />
              <el-table-column prop="type" label="区块类型" width="120">
                <template #default="{ row }">
                  <el-tag>{{ getBlockTypeLabel(row.type) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="80">
                <template #default="{ row }">
                  <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                    {{ row.status === 1 ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="{ row }">
                  <el-button size="small" @click.stop="testLoadFields(row)">
                    测试加载字段
                  </el-button>
                  <el-button size="small" type="primary" @click.stop="goToConfig(row)">
                    配置字段
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
        
        <!-- 字段配置预览 -->
        <el-col :span="12">
          <h4>字段配置预览</h4>
          <div v-if="!selectedBlock" style="text-align: center; padding: 40px;">
            <el-empty description="请选择一个区块查看字段配置" />
          </div>
          
          <div v-else>
            <el-descriptions border :column="1" style="margin-bottom: 16px;">
              <el-descriptions-item label="区块名称">{{ selectedBlock.name }}</el-descriptions-item>
              <el-descriptions-item label="区块类型">{{ getBlockTypeLabel(selectedBlock.type) }}</el-descriptions-item>
              <el-descriptions-item label="字段数量">{{ fields.length }}</el-descriptions-item>
            </el-descriptions>
            
            <div v-loading="fieldsLoading">
              <div v-if="fields.length === 0" style="text-align: center; padding: 20px;">
                <el-empty description="该区块暂无字段配置" />
                <el-button type="primary" @click="testInitDefaultFields" style="margin-top: 16px;">
                  初始化默认字段
                </el-button>
              </div>
              
              <el-table v-else :data="fields" border size="small">
                <el-table-column prop="name" label="字段名" width="120" />
                <el-table-column prop="label" label="标签" width="120" />
                <el-table-column prop="type" label="类型" width="100">
                  <template #default="{ row }">
                    <el-tag size="small">{{ row.type }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="required" label="必填" width="60">
                  <template #default="{ row }">
                    <el-tag :type="row.required ? 'danger' : 'info'" size="small">
                      {{ row.required ? '是' : '否' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" show-overflow-tooltip />
              </el-table>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <el-divider />
      
      <!-- 测试操作 -->
      <h4>测试操作</h4>
      <el-space wrap>
        <el-button @click="testCreateBlock">创建测试区块</el-button>
        <el-button @click="testBatchLoadFields" :loading="batchLoading">批量加载字段</el-button>
        <el-button @click="testDefaultFieldsAPI">测试默认字段API</el-button>
        <el-button @click="clearTestResults">清空测试结果</el-button>
      </el-space>
      
      <el-divider />
      
      <!-- 测试结果 -->
      <h4>测试结果</h4>
      <div class="test-results">
        <div v-for="(result, index) in testResults" :key="index" class="test-result">
          <el-alert
            :title="result.title"
            :type="result.type"
            :description="result.description"
            show-icon
            :closable="false"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { blockApi } from '@/api/block'

const router = useRouter()

// 响应式数据
const blocks = ref<any[]>([])
const selectedBlock = ref<any>(null)
const fields = ref<any[]>([])
const blocksLoading = ref(false)
const fieldsLoading = ref(false)
const batchLoading = ref(false)
const testResults = ref<any[]>([])

// 区块类型映射
const blockTypeMap: Record<string, string> = {
  'carousel': '轮播图',
  'article_list': '文章列表',
  'news': '新闻',
  'activity': '活动',
  'discussion': '讨论',
  'image': '图片',
  'text': '文本',
  'html': 'HTML',
  'video': '视频',
  'list': '列表',
  'custom': '自定义'
}

// 方法
const getBlockTypeLabel = (type: string) => {
  return blockTypeMap[type] || type
}

const addTestResult = (title: string, type: 'success' | 'warning' | 'error' | 'info', description: string) => {
  testResults.value.unshift({
    title,
    type,
    description,
    time: new Date().toLocaleTimeString()
  })
  
  // 只保留最近10条结果
  if (testResults.value.length > 10) {
    testResults.value = testResults.value.slice(0, 10)
  }
}

const loadBlocks = async () => {
  blocksLoading.value = true
  try {
    const response = await blockApi.getList({ current: 1, size: 100 })
    if (response.code === 0) {
      blocks.value = response.data?.records || response.data?.list || []
      addTestResult('加载区块列表', 'success', `成功加载${blocks.value.length}个区块`)
    }
  } catch (error) {
    addTestResult('加载区块列表', 'error', '加载失败')
    ElMessage.error('加载区块列表失败')
  } finally {
    blocksLoading.value = false
  }
}

const selectBlock = (row: any) => {
  selectedBlock.value = row
  testLoadFields(row)
}

const testLoadFields = async (block: any) => {
  fieldsLoading.value = true
  try {
    console.log('测试加载字段配置:', block.id)
    const response = await blockApi.getFields(block.id)
    console.log('字段配置响应:', response)
    
    if (response.code === 0) {
      fields.value = response.data || []
      addTestResult(
        '加载字段配置', 
        'success', 
        `${block.name}: 成功加载${fields.value.length}个字段`
      )
    } else {
      addTestResult('加载字段配置', 'warning', `${block.name}: ${response.msg}`)
    }
  } catch (error) {
    addTestResult('加载字段配置', 'error', `${block.name}: 加载失败`)
    console.error('加载字段配置失败:', error)
  } finally {
    fieldsLoading.value = false
  }
}

const testInitDefaultFields = async () => {
  if (!selectedBlock.value) return
  
  try {
    const response = await blockApi.getDefaultFields(selectedBlock.value.type)
    if (response.code === 0 && response.data && response.data.length > 0) {
      addTestResult(
        '默认字段初始化', 
        'success', 
        `${selectedBlock.value.type}类型有${response.data.length}个默认字段`
      )
    } else {
      addTestResult(
        '默认字段初始化', 
        'warning', 
        `${selectedBlock.value.type}类型暂无默认字段模板`
      )
    }
  } catch (error) {
    addTestResult('默认字段初始化', 'error', '获取默认字段失败')
  }
}

const testBatchLoadFields = async () => {
  batchLoading.value = true
  let successCount = 0
  let errorCount = 0
  
  try {
    for (const block of blocks.value.slice(0, 5)) { // 只测试前5个
      try {
        const response = await blockApi.getFields(block.id)
        if (response.code === 0) {
          successCount++
        } else {
          errorCount++
        }
      } catch (error) {
        errorCount++
      }
    }
    
    addTestResult(
      '批量加载测试', 
      successCount > errorCount ? 'success' : 'warning', 
      `成功: ${successCount}, 失败: ${errorCount}`
    )
  } finally {
    batchLoading.value = false
  }
}

const testDefaultFieldsAPI = async () => {
  const testTypes = ['carousel', 'news', 'activity', 'custom']
  
  for (const type of testTypes) {
    try {
      const response = await blockApi.getDefaultFields(type)
      const count = response.data?.length || 0
      addTestResult(
        `默认字段API测试`, 
        count > 0 ? 'success' : 'info', 
        `${type}: ${count}个默认字段`
      )
    } catch (error) {
      addTestResult('默认字段API测试', 'error', `${type}: 请求失败`)
    }
  }
}

const testCreateBlock = async () => {
  try {
    const testBlock = {
      name: `测试区块_${Date.now()}`,
      alias: `test_block_${Date.now()}`,
      type: 'custom',
      description: '这是一个测试区块',
      status: 1
    }
    
    const response = await blockApi.create(testBlock)
    if (response.code === 0) {
      addTestResult('创建测试区块', 'success', `成功创建: ${testBlock.name}`)
      await loadBlocks() // 重新加载列表
    } else {
      addTestResult('创建测试区块', 'error', response.msg || '创建失败')
    }
  } catch (error) {
    addTestResult('创建测试区块', 'error', '创建失败')
  }
}

const goToConfig = (block: any) => {
  router.push(`/config/block`)
  ElMessage.info(`跳转到区块配置页面: ${block.name}`)
}

const clearTestResults = () => {
  testResults.value = []
  addTestResult('清空测试结果', 'info', '测试结果已清空')
}

onMounted(() => {
  loadBlocks()
})
</script>

<style scoped lang="scss">
.dynamic-block-config-test {
  padding: 20px;
  
  h4 {
    margin: 16px 0 12px 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
  
  .test-results {
    .test-result {
      margin-bottom: 12px;
    }
  }
  
  .el-table {
    cursor: pointer;
    
    .el-table__row:hover {
      background-color: #f5f7fa;
    }
  }
}
</style>
